const getInfo = wx.getAccountInfoSync();
const envVersion = getInfo.miniProgram.envVersion;
const baseUrl = envVersion == "release" ? 'https://photo.visiondefender.cn' : 'https://photo.visiondefender.cn';

// 接口封装 get post 请求
const httpServer = (method, url, param) => {
  return new Promise((resolve, reject) => {
    wx.request({
      method: method,
      url: `${ baseUrl }${ url }`, //接口地址
      data: param, //接收的参数
      dataType: 'json',
      header: {
        token: wx.getStorageSync('userinfo').token || '',
        'content-type': 'application/json', // 头部格式
      },
      // 成功回调
      success(res) {
        console.log('url:', url, '入口参数：', param, '返回参数：', res)
        const { data } = res;
        const { code, message, msg } = data;
        if (code == 200 || code == 1) {
          resolve(data);
        } else if (code == 401) {
          wx.navigateTo({
            url: '/pages/login/login',
          })
          resolve(data);
        } else {
          let message1 = "请稍后重试！";

          setTimeout(() => {
            wx.showToast({
              title: message || msg || message1,
              duration: 3000,
              mask: true,
              icon: 'none',
            });
          })
          reject(res.data);
        }
        wx.stopPullDownRefresh();
      },
      // 失败回调
      fail(err) {
        console.error('err123', 'url:', url, "error:", err)
        wx.showToast({
          title: '网络异常',
          duration: 3000,
          mask: true,
        });
        reject(err);
        wx.stopPullDownRefresh();
      },
      // 回调结束
      complete(cmp) {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      },
    });
  });
};

module.exports = httpServer;
